<template>
  <div :style="{ marginBottom: isEdit ? '22px' : ''}" class="info-wrap">
    <Title :title="isNewVersion? '当前签约状态' : '历史签约状态'" :style="{ marginTop: '10px !important'}" style="font-size:16px; margin:32px 0 8px 0"/>
    <el-form
      :class="{'mobile-el-form': showMobilePage}"
      :label-position="showMobilePage?'left':'right'"
      label-width="110px"
      class="supplier-form height55">
      <el-row :gutter="20" :class="{'col-dividing': !showMobilePage}">
        <el-col :span="12">
          <el-form-item label="签约状态：" class="flex-form-row">
            <div class="status-wrap">
              <div v-if="getStatusMap()" class="flex-center">
                <div :style="{background: getStatusMap().bg}" class="status-text">{{ getStatusMap().status }}</div>
                <span v-if="getStatusMap().remark" class="f12 g3 ml5">{{ getStatusMap().remark }}</span>
              </div>
              <span v-else>--</span>
              <span v-if="!isEdit && isNewVersion" class="ml8 link-btn" @click="openStatusDialog">状态变更日志</span>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="自动续约：" class="flex-form-row">
            <template v-if="canChangeAutoRenewal && isNewVersion">
              <el-dropdown
                :hide-on-click="true"
                class="renewal-value"
                @command="renewalStatusChange($event)">
                <span class="el-dropdown-link">
                  {{ renewalStatus[detailInfo.additionalKey.autoRenewal] || '--' }}
                  <i class="el-icon-arrow-down el-icon--right" />
                </span>
                <el-dropdown-menu slot="dropdown" class="renewal-dropdown">
                  <el-dropdown-item :command="0">否</el-dropdown-item>
                  <el-dropdown-item :command="1">是</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
              <el-select
                v-if="detailInfo.additionalKey.autoRenewal === 1"
                v-model="detailInfo.additionalKey.renewalTime"
                placeholder="续约时长"
                size="small"
                class="renewalTime"
                @change="renewalTimeChange"
              >
                <el-option
                  v-for="(select, index) in renewalTimeOptions"
                  :key="index"
                  :label="select.label"
                  :value="select.value" />
              </el-select>
            </template>
            <div v-else>{{ renewalStatus[detailInfo.additionalKey.autoRenewal] || '--' }}</div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="关联签约：" prop="terminationNum" style="margin-bottom: 0px;">
            <div class="flex-center">
              <ToolTip
                :label-style="signIsExpired?{
                  color: '#999'
                }:{}"
                :content="getSn(detailInfo.additionalKey.signLink)"
                :is-can-click="!!(detailInfo.additionalKey.signLink && detailInfo.additionalKey.signLink.id)"
                placement="top"
                @handelClick="goSignUpDetail"/>
              <span v-if="!isEdit" class="ml8 link-btn" @click="toList('signUp')">查看所有签约</span>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="签约有效期：" style="margin-bottom: 0px;">
            <template slot-scope="scope">
              <ToolTip :content="formatSignDate(detailInfo)"/>
            </template>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="签约合同：" style="margin-bottom: 0px;">
            <div class="legal-content">
              <div v-if="showSignContractName" style="display: flex;">
                <ToolTip
                  :content="handleLegalName(detailInfo.additionalKey.signLegal)"
                  :label-style="legalIsExpired?{
                    color: '#999'
                  }:{}"
                  is-can-click
                  style="margin-right: 8px;"
                  placement="top"
                  @handelClick="toContractDetail(detailInfo.additionalKey.signLegal)"/>
              </div>
              <span v-else class="mr5">--</span>
              <div class="col-flex">
                <div>
                  <el-button
                    v-if="canRelatedContract && isNewVersion"
                    plain
                    size="small"
                    type="primary"
                    class="related-btn"
                    style="height: 30px; width: 110px;"
                    @click="relatedContractShow">关联签约合同</el-button>
                  <span v-if="!isEdit" class="ml8 link-btn" @click="toList('legal')">查看所有合同</span>
                </div>
                <span v-if="showRelatedContractTip" class="stamp-fixed-tip">
                  <i class="el-icon-warning" />
                  <span>请关联新的签约合同</span>
                </span>
              </div>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="合同有效期：" style="margin-bottom: 0px;">
            <template slot-scope="scope">
              <span v-if="showLegalTime">
                {{ detailInfo.additionalKey.signLegal.validityStart | format('YYYY/MM/DD') }}-{{ detailInfo.additionalKey.signLegal.validityEnd | format('YYYY/MM/DD') }}
              </span>
              <span v-else>--</span>
              <span v-if="signDetailStatus === SIGN_DETAIL_STATUS.WAIT_SIGN">(无合同)</span>
              <span v-else-if="signDetailStatus === SIGN_DETAIL_STATUS.AUTO_RENEWAL">(无新合同)</span>
              <template v-else-if="[SIGN_DETAIL_STATUS.SIGNED, SIGN_DETAIL_STATUS.RENEWAL].includes(signDetailStatus)">
                <span v-if="detailInfo.moreAccountInfo.isExpired">(<span style="color: #FF4E5F;">已到期</span>)</span>
                <span v-else>(距离到期日： <span :style="expiredTypeClass(detailInfo.moreAccountInfo.expiredDuration)">
                  {{ getExpiredDuration() }}</span> 天)
                </span>
              </template>
              <span v-else>(距离到期日： -- 天)</span>
            </template>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="关联解约：" prop="terminationNum" style="margin-bottom: 0px;">
            <div class="flex-center">
              <ToolTip
                :label-style="terminationIsExpired?{
                  color: '#999'
                }:{}"
                :content="getSn(detailInfo.additionalKey.terminationLink)"
                :is-can-click="!!(detailInfo.additionalKey.terminationLink && detailInfo.additionalKey.terminationLink.id)"
                placement="top"
                @handelClick="goTerminationDetail"/>
              <span v-if="!isEdit" class="ml8 link-btn" @click="toList('termination')">查看所有解约</span>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <!-- 关联合同 -->
    <relatedContract
      ref="showRelatedContract"
      :multiple="false"
      :visible.sync="showRelatedContract"
      exclude-cancel
      @confirmRelatedContract="confirmRelatedContract"
    />
    <statusLogDialog v-if="!isEdit" ref="statusDialog"/>
  </div>
</template>
<script>
import { mapState } from 'vuex';
import { format } from '@/filters/date';
import relatedContract from '@/components/CreateOrder/relatedContract';
import Title from '@/components/Title';
import statusLogDialog from '@/views/resource/components/statusLog';
import { CONTRACT_TYPE } from '@/utils/const/contract';
import { SIGN_DETAIL_STATUS } from '@/utils/const/resouce';
import { hasRouteAuth } from '@/utils/permission';
import { showModal } from '@/utils/message';
import { encryption } from '@/utils';
import { editAccountRenewal, associateContractRenewal } from '@/api/signUp';
import { expiredTypeClass } from '@/views/signUp/components/status';
import { getStatusMap } from '@/filters/status';

export default {
  components: { Title, relatedContract, statusLogDialog },
  filters: { format },
  props: {
    detailInfo: {// 详情信息
      type: Object,
      default: () => {}
    },
    processFinished: {
      type: Boolean,
      default: false
    },
    isEdit: {
      type: Boolean,
      default: false
    },
    isNewVersion: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      SIGN_DETAIL_STATUS,
      showRelatedContract: false,
      renewalTimeOptions: [
        { value: 0, label: '一年' },
        { value: 1, label: '两年' }
      ]
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    }),
    renewalStatus() {
      return {
        0: '否',
        1: '是'
      };
    },
    signDetailStatus() {
      return this.detailInfo.moreAccountInfo.signDetailStatus;
    },
    legalIsExpired() {
      return this.detailInfo.moreAccountInfo.isExpired;
    },
    signIsExpired() {
      const { isExpired } = this.detailInfo.additionalKey.signLink || {};
      return isExpired;
    },
    terminationIsExpired() {
      const { isExpired } = this.detailInfo.additionalKey.terminationLink || {};
      return !isExpired;
    },
    // 关联新的签约合同提示
    showRelatedContractTip() {
      const { autoRenewal } = this.detailInfo.additionalKey;
      return autoRenewal === 1 && this.signDetailStatus === SIGN_DETAIL_STATUS.AUTO_RENEWAL && !this.isEdit;
    },
    // 关联签约合同前置条件
    canRelatedContract() {
      return [SIGN_DETAIL_STATUS.WAIT_SIGN, SIGN_DETAIL_STATUS.SIGNED, SIGN_DETAIL_STATUS.RENEWAL, SIGN_DETAIL_STATUS.AUTO_RENEWAL].includes(this.signDetailStatus) && !this.isEdit;
    },
    showSignContractName() {
      if (!this.detailInfo.additionalKey.signLegal) return false;
      const { contractCode, contractName, draft } = this.detailInfo.additionalKey.signLegal || {};
      return contractCode || contractName || draft;
    },
    // (有总编辑权限且有签约信息编辑权限&非已解约&详情页)
    canChangeAutoRenewal() {
      return hasRouteAuth('medium:dataEdit:signInfo') && this.detailInfo.isEditAuth && this.detailInfo.signStatus !== -1 && !this.isEdit;
    },
    showLegalTime() {
      return this.detailInfo.additionalKey.signLegal && this.detailInfo.additionalKey.signLegal.processId && this.detailInfo.additionalKey.signLegal.validityStart;
    }
  },
  methods: {
    expiredTypeClass,
    format,
    // 选择合同
    relatedContractShow() {
      this.showRelatedContract = true;
      const legalCode = this.detailInfo.additionalKey.legalCode || null;
      this.$refs['showRelatedContract'].filterInput = { contractType: CONTRACT_TYPE.KOL };
      this.$refs['showRelatedContract'].init(legalCode);
    },
    handleLegalName(legal) {
      if (!legal) return '--';
      if (legal.contractCode || legal.contractName) {
        return legal.contractCode || legal.contractName;
      }
      if (legal.draft) {
        return '草稿中';
      }
    },
    confirmRelatedContract(data) {
      const contractId = data && data.id || null;
      if (!contractId) {
        this.$message.warning('无效合同，请重新选择');
        return;
      }
      showModal('确认关联此合同吗？').then(() => {
        const params = { contractId };
        params.ids = `${this.detailInfo.id}`;
        associateContractRenewal(params).then(res => {
          res.code === 200 && this.$message.success('关联成功');
        }).finally(() => {
          this.$emit('success');
          this.showRelatedContract = false;
        });
      });
    },
    // 跳转详情
    toContractDetail(data) {
      let routeUrl = '';
      if (data.draft) {
        routeUrl = this.$router.resolve({
          name: 'EditContract',
          params: {
            id: encryption(data.id)
          }
        });
      } else {
        routeUrl = this.$router.resolve({
          name: 'contractDetail',
          params: { id: encryption(data.id) },
          query: {
            processId: encryption(data.processId)
          }
        });
      }
      window.open(routeUrl.href, '_blank');
    },
    renewalTimeChange(renewalTime) {
      const params = {
        status: this.detailInfo.additionalKey.autoRenewal,
        renewalTime: renewalTime,
        accountInfoId: this.detailInfo.id
      };
      editAccountRenewal(params).then(res => {
        res.code === 200 && this.$message.success('操作成功');
      }).finally(() => {
        this.$emit('success');
      });
    },
    renewalStatusChange(status) {
      showModal('确认变更自动续约状态吗？').then(() => {
        const params = {
          status,
          renewalTime: status === 0 ? null : 0, // 默认一年
          accountInfoId: this.detailInfo.id
        };
        editAccountRenewal(params).then(res => {
          res.code === 200 && this.$message.success('操作成功');
        }).finally(() => {
          this.$emit('success');
        });
      });
    },
    // 跳转至达人解约详情
    goTerminationDetail() {
      const { id, processId } = this.detailInfo.additionalKey.terminationLink || {};
      const routeUrl = this.$router.resolve({
        name: 'terminationDetail',
        query: {
          terminationId: id,
          processId: processId
        }
      });
      window.open(routeUrl.href, '_blank');
    },
    getExpiredDuration() {
      const { expiredDuration } = this.detailInfo.moreAccountInfo || {};
      return ((expiredDuration || expiredDuration === 0) && expiredDuration !== 9999) ? expiredDuration : '--';
    },
    // 跳转至签约内审详情
    goSignUpDetail() {
      const { id, processId } = this.detailInfo.additionalKey.signLink || {};
      const routeUrl = this.$router.resolve({
        name: 'signUpDetail',
        query: {
          signUpId: id,
          processId: processId
        }
      });
      window.open(routeUrl.href, '_blank');
    },
    toList(routeName) {
      const { resourceId, platformType } = this.detailInfo || {};
      const routeUrl = this.$router.resolve({
        name: routeName,
        query: {
          accountId: resourceId,
          platformId: platformType
        }
      });
      window.open(routeUrl.href, '_blank');
    },
    getSn(data = {}) {
      if (!data) return '';
      return data.sn || '';
    },
    formatSignDate(detailInfo) {
      const { signDate } = detailInfo.additionalKey;
      if (signDate && (signDate[0] || signDate[1])) {
        return this.format(signDate[0], 'YYYY/MM/DD') + '-' + this.format(signDate[1], 'YYYY/MM/DD');
      } else {
        return '--';
      }
    },
    openStatusDialog() {
      this.$refs.statusDialog.openDialog(this.detailInfo.id);
    },
    getStatusMap() {
      const { signDetailStatus } = this.detailInfo.moreAccountInfo;
      return getStatusMap(signDetailStatus);
    }
  }
};
</script>
<style lang="scss" scoped>
  ::v-deep {
    .el-form-item__label{
      color: #999999 !important;
    }
    .el-form-item__content {
      color: #333 !important;
    }
  }
  .flex-form-row {
    margin-bottom: 0 !important;
    ::v-deep {
      .el-form-item__content {
        display: flex;
        align-items: center;
        color: #333 !important;
      }
    }
  }
  .renewal-value {
    &::v-deep {
      > .el-dropdown-link {
        cursor: default !important;
        color: #333;
        font-size: 14px;
      }
      > .el-dropdown-selfdefine {
        cursor: pointer !important;
        &:hover {
          color: #406EFF;
        }
      }
    }
  }
  .related-btn {
    padding-left: 12px;
    padding-right: 12px;
  }
  .renewalTime {
    width: 100px;
    margin-left: 12px;
  }
  .link-btn {
    white-space: nowrap;
    color: #406EFF;
    cursor: pointer;
  }
  .legal-content {
    display: flex;
    .col-flex {
      display: flex;
      flex-direction: column;
    }
  }
  .stamp-fixed-tip {
    width: 175px;
    z-index: 999;
    background-color: #FFF8EA;
    border-radius: 4px;
    font-size: 14px;
    padding: 3px 22px 3px 8px;
    line-height: 24px;
    margin-top: 8px;
    span {
      color: #333;
    }
    .icon {
      cursor: pointer;
      margin-left: 8px;
      color: #C0C4CC;
      &:hover {
        color: #909399;
      }
    }
    ::v-deep .el-icon-warning {
      color: #E6A23C;
    }
  }
  .status-wrap {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 32px;
    .status-text {
      width: 48px;
      height: 20px;
      display: flex;
      justify-content: center;
      align-items: center;
      color: #fff;
      border-radius: 10px;
      font-size: 12px;
    }
  }
  .col-dividing {
    ::v-deep {
      .el-col {
        .el-form-item__content {
          border-right: 1px solid #EBEEFD;
        }
        &:nth-child(2n) {
          .el-form-item__content {
            border-right: none;
          }
        }
        &:last-child {
          .el-form-item__content {
            border-right: none;
          }
        }
      }
    }
  }
</style>
